package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.*;
import com.example.demo.mapper.IntegralMapper;
import com.example.demo.mapper.attentionMapper;
import com.example.demo.mapper.blogMapper;
import com.example.demo.mapper.usersMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
public class usersController {
    @Autowired
    usersMapper usersMapper;
    @Autowired
    blogMapper blogMapper;
    @Autowired
    attentionMapper attentionMapper;
    @Autowired
    IntegralMapper integralMapper;

    //根据邮箱查找用户
    @GetMapping("/selectuser/{mailbox}")
    public users selectuser(@PathVariable("mailbox") String mailbox) {
        return usersMapper.selectuser(mailbox);
    }

    //返回个人资料
    @GetMapping("/personal/{mailbox}")
    public String personal(@PathVariable("mailbox") String mailbox) throws ParseException {
        List<blog> blogList = blogMapper.selectblogBymailbox(mailbox);
        if (blogList.size() == 0) {
            users users = usersMapper.selectuser(mailbox);
            blogdata blogdata = new blogdata();
            blogdata.setFans(0);
            blogdata.setQriginal(0);
            blogdata.setGrade(1);
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
            Date d2 = df.parse(users.getFirstlinecode());
            Date d1 = new Date();
            long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
            long days = diff / (1000 * 60 * 60 * 24);
            blogdata.setCodeage(Double.parseDouble(String.format("%.1f", days * 1.0 / 365.0)));
            blogdata.setUsers(users);
            return blogdata.toString();
        }
        blog blog = blogMapper.selectblogByid(blogList.get(0).getId());
        users users = usersMapper.selectuser(blog.getUser());
        //查询用户的所有博客
        List<blog> blogs = blogMapper.selectblogBymailbox(blog.getUser());
        blogdata blogdata = new blogdata();
        for (int i = 0; i < blogs.size(); i++) {
            blogdata.setBrowse(blogs.get(i).getBrowse() + blogdata.getBrowse());
            blogdata.setComment(blogs.get(i).getComment() + blogdata.getComment());
            blogdata.setFabulous(blogs.get(i).getFabulous() + blogdata.getFabulous());
            blogdata.setCollection(blogs.get(i).getCollection() + blogdata.getCollection());
        }
        attention a = new attention();
        a.setT(users.getMailbox());
        //假数据，粉丝数量
        blogdata.setFans(attentionMapper.selectFans(a).size());
        blogdata.setQriginal(blogs.size());
        blogdata.setGrade(users.getGrade());
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        Date d2 = df.parse(users.getFirstlinecode());
        Date d1 = new Date();
        long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
        long days = diff / (1000 * 60 * 60 * 24);
        blogdata.setCodeage(Double.parseDouble(String.format("%.1f", days * 1.0 / 365.0)));
        blogdata.setUsers(users);
        return blogdata.toString();
    }

    //个人资料修改
    @GetMapping("/updateusers/{mailbox}/{name}/{birthday}/{gender}/{nickname}/{autograph}/{firstlinecode}")
    public String updateusers(@PathVariable String name, @PathVariable String birthday,
                              @PathVariable String gender, @PathVariable String nickname,
                              @PathVariable String autograph, @PathVariable String firstlinecode,
                              @PathVariable String mailbox) {
        birthday = birthday.replace("-", "/");
        firstlinecode = firstlinecode.replace("-", "/");
        users u = new users();
        u.setName(name);
        u.setNickname(nickname);
        u.setMailbox(mailbox);
        u.setGender(gender);
        u.setAutograph(autograph);
        u.setBirthday(birthday);
        u.setFirstlinecode(firstlinecode);
        usersMapper.updateusers(u);
        return u.toString();
    }

    //注册用户
    @PostMapping(value = "/registeruser", produces = "application/json;charset=UTF-8")
    public String registeruser(@RequestBody JSONObject jsonObject) throws IOException {
        users users = new users();
        users.setAutograph(jsonObject.getString("autograph"));
        users.setBirthday(jsonObject.getString("birthday").replace("-", "/"));
        if (jsonObject.getString("gender").equals("1")) {
            users.setGender("男");
        } else {
            users.setGender("女");
        }
        users.setNickname(jsonObject.getString("nickname"));
        users.setPassword(jsonObject.getString("password"));
        users.setMailbox(jsonObject.getString("mailbox"));
        users.setFirstlinecode(jsonObject.getString("firstlinecode").replace("-", "/"));
        users.setGrade(0);
        users.setName(jsonObject.getString("name"));
        if (usersMapper.selectuser(users.getMailbox()) != null) {
            return "已注册过了这个邮箱，忘记密码请联系管理员";
        }
        usersMapper.registeruser(users);
        Integral integral = new Integral();
        integral.setMailbox(users.getMailbox());
        integral.setIntegral(0);
        integralMapper.insertintegral(integral);

        String str[] = {
                "C:/manongyizhanFile/users/" + users.getMailbox() + "/blog",
                "C:/manongyizhanFile/users/" + users.getMailbox() + "/头像",
                "C:/manongyizhanFile/users/" + users.getMailbox() + "/网盘"
        };
        File f = new File("C:/manongyizhanFile/users/" + users.getMailbox());
        if (!f.exists()) {//如果文件夹不存在
            f.mkdir();//创建文件夹
        }
        for (int i = 0; i < 3; i++) {
            File file = new File(str[i]);
            if (!file.exists()) {//如果文件夹不存在
                file.mkdir();//创建文件夹
            }
        }
        File source = new File("C:/manongyizhanFile/头像/mrtx.jpg");
        File dest = new File("C:/manongyizhanFile/users/" + users.getMailbox() + "/头像", users.getMailbox() + ".jpg");
        Files.copy(source.toPath(), dest.toPath());
        return "ok";
    }

    @PostMapping(value = "/login", produces = "application/json;charset=UTF-8")
    public String login(@RequestBody JSONObject jsonObject) {
        users users = new users();
        users.setMailbox(jsonObject.getString("mailbox"));
        users.setPassword(jsonObject.getString("password"));
        if (usersMapper.login(users) != null) {
            return "ok";
        } else {
            return "no";
        }
    }

    //头像修改
    @PostMapping(value = "/headportrait/{mailbox}")
    public String headportrait(MultipartFile file, @PathVariable String mailbox) throws IOException {
        String path = "C:/manongyizhanFile/users/" + mailbox + "/头像/" + mailbox + ".jpg";
        File file1 = new File(path);
        file1.delete();
        path = "C:/manongyizhanFile/users/" + mailbox + "/头像";
        File dest = new File(path, mailbox + ".jpg");
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        if (!dest.exists()) {
            dest.mkdirs();
        }
        try {
            file.transferTo(dest); //保存文件
            return "ok";
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "no";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "no";
        }
    }

}
